import os
import subprocess


Modules_Scan_Dir = '' # ./x86modules/



def readcpu():
    f = open(os.path.dirname(os.path.realpath(__file__)) + '/cpu.conf')
    for line in f.readlines():
        if line.split(sep='=')[0] == 'cpu':
            cpuinfo = line.split(sep='=')[1].lstrip().rstrip()
            global Modules_Scan_Dir
            Modules_Scan_Dir = os.path.dirname(os.path.realpath(__file__)) + '/{}modules/'.format(cpuinfo)
    f.close()

# 负责搜寻可用模块
def scan_modules():
    mod = []
    print('扫描架构：', os.path.relpath(Modules_Scan_Dir)[:-7])
    for dirname in os.listdir(Modules_Scan_Dir):
        if os.path.isdir(Modules_Scan_Dir + dirname):  # 判断文件名称是不是目录
            mark_conf = 0  # 配置文件标志位   没有文件0 有文件1
            mark_startup = 0  # 启动文件标志位   没有文件0 有文件1
            key = ''
            value = ''
            for file in os.listdir(Modules_Scan_Dir + dirname):  # 遍历所有文件名，判断是否有info.conf配置文件，以及startup开头的启动文件
                if file == 'info.conf':
                    mark_conf = 1
                if file == 'startup.py' or file == 'startup.sh':    # 判断是否有启动文件 startup.py 或者 startup.sh
                    mark_startup = 1

            if mark_conf and mark_startup:
               mod.append(dirname)
    mod.sort()
    return mod
                # mod 的样子 ['python', 'go', 'fastjson']


def switch_mod_menu(modlist):
    # 显示选项
    author = ''
    for i in range(len(modlist)):
        dir = Modules_Scan_Dir + modlist[i]
        for file in os.listdir(dir):    # 遍历模块A中所有的文件
            if file == 'info.conf':
                f = open(Modules_Scan_Dir + modlist[i] + '/info.conf', 'r') # 打开文件./x86modules/go/info.conf
                for line in f.readlines():  # 逐行读取info.conf文件
                    if line.split('=')[0] == 'author' and len(line.split('=')) == 2:
                        author = '  (模块开发者：{})'.format(line.split('=')[1]).lstrip().rstrip()
                f.close()
        print('选项{}：  %-15s  {}'.format(i+1, author) % modlist[i])
    print('\n##################################################\n'
          '    软件名：PBMautotest\n'
          '    用途：服务器系统兼容测试自动安装工具\n'
          '    特点：拥有可扩展性，可统一接管，自动安装需要的版本\n'
          '    测试框架开发者：麒麟软件天津事业部刘汉霆\n'
          '    版本：测试版，仅可用于纯净系统测试机。     注意：请用root权限运行\n'
          '##################################################')
    while True:
        choose = input('====> 请选择想要测试安装的软件: \n')
        if choose.isdigit():
            choose = int(choose)
            if choose < 0 or choose > len(modlist):
                print('Warning: 选择错误，选项不存在')
            else:
                modname = modlist[choose-1]
                print('Notice：您选择的模块为 {}'.format(modname))
                return modname
        else:
            print('Warning：选择错误，请输入数字')


def startupmethod(modname):
    value = ''
    for file in os.listdir(Modules_Scan_Dir + modname):
        if file.split(sep='.')[0] == 'startup' and len(file.split(sep='.')) == 2:
            if file.split(sep='.')[1] == 'sh':
                value = 'bash {}/startup.sh'.format(Modules_Scan_Dir + modname)
            if file.split(sep='.')[1] == 'py':
                value = 'python3 {}/startup.py'.format(Modules_Scan_Dir + modname)
    return value


def alter(file, old_str, new_str):
    file_data = ""
    with open(file, "r", encoding="utf-8") as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str, new_str)
            file_data += line
    with open(file, "w", encoding="utf-8") as f:
        f.write(file_data)
    f.close()

def check_mod_version(modname):
    print('====> 选择{}安装的版本'.format(modname))
    f = open(Modules_Scan_Dir + '{}/info.conf'.format(modname))
    version = ''
    for line in f.readlines():
        if line.split('=')[0] == 'version' and len(line.split('=')) == 2:
            version = line.split('=')[1].lstrip().rstrip()
    f.close()
    if version:
        print('当前版本为：{}'.format(version))
        needversion = input('请输入版本号 （使用默认版本，请直接回车）：')
        if needversion != '':
            alter(Modules_Scan_Dir + '{}/info.conf'.format(modname), version, needversion)
            print('版本设定完成，新设定版本为：{}'.format(needversion))
        else:
            print('使用默认版本 {}'.format(version))
    else:
        print('Error：未读取到version版本信息')

def runcmd(command):    # linux命令通过该函数运行
    print('Notice：执行命令 —— CMD={}'.format(command))
    p = subprocess.Popen(command, shell=True)
    p.wait()
    if p.returncode != 0:
        print('!!!!Error：执行失败 —— CMD={}'.format(command))




if __name__ == '__main__':
    readcpu()
    modlist = scan_modules()
    modname = switch_mod_menu(modlist)
    cmd = startupmethod(modname)    # 模块启动命令
    check_mod_version(modname)
    print('CMD= {}'.format(cmd))
    runcmd(cmd)
    print('如有问题，可联系作者反馈：麒麟软件天津事业部刘汉霆')



